import React, { PureComponent } from 'react';
import {
  Card,
  Button,
  Tree,
  Form,
  Input,
  Icon,
  Spin,
  Modal,
  Row,
  Select,
  Col
} from 'antd';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from "./Menu.less";

const FormItem = Form.Item;
const { TreeNode } = Tree;
const { Option } = Select;

@connect(({ authMenu, loading }) => ({
  authMenu,
  loading: loading.models.authMenu,
}))
@Form.create()
class AddOrUpdateForm extends PureComponent {

  okHandle = () => {
    const { form, handleAdd, handleUpdate, authMenu: { data } } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if (Object.keys(data).length) {
        handleUpdate(fieldsValue)
      } else {
        handleAdd(fieldsValue);
      }
    });
  }

  render() {
    const { form, authMenu: { data } } = this.props;
    return (
      <Form>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="父ID">
          {form.getFieldDecorator('parentId', {
            initialValue: data && Object.keys(data).length ? data.parentId : '',
            rules: [{ required: true, message: '父ID必填！' }],
          })(
            <Input disabled={Object.keys(data).length > 0} />
          )}
        </FormItem>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="ID">
          {form.getFieldDecorator('menuId', {
            initialValue: data && Object.keys(data).length ? data.menuId : '',
            rules: [{ required: true, message: 'ID必填！' }],
          })(
            <Input disabled={Object.keys(data).length > 0} />
          )}
        </FormItem>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="名称">
          {form.getFieldDecorator('menuName', {
            initialValue: data && Object.keys(data).length ? data.menuName : '',
            rules: [{ required: true, message: '名称必填！' }],
          })(
            <Input disabled={!data} />
          )}
        </FormItem>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="描述">
          {form.getFieldDecorator('menuDesc', {
            initialValue: data && Object.keys(data).length ? data.menuDesc : '',
            rules: [{ required: true, message: '描述必填！' }],
          })(
            <Input disabled={!data} />
          )}
        </FormItem>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="路由">
          {form.getFieldDecorator('menuPath', {
            initialValue: data && Object.keys(data).length ? data.menuPath : '',
          })(
            <Input disabled={!data} />
          )}
        </FormItem>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="图标">
          {form.getFieldDecorator('icon', {
            initialValue: data && Object.keys(data).length ? data.icon : '',
          })(
            <Input disabled={!data} />
          )}
        </FormItem>
        <Form.Item
          wrapperCol={{ span: 12, offset: 5 }}
        >
          <Button type="primary" onClick={() => this.okHandle()}>
            提交
          </Button>
        </Form.Item>
      </Form>
    )
  }
}

/* eslint react/no-multi-comp:0 */
@connect(({ authMenu, loading }) => ({
  authMenu,
  loading: loading.models.authMenu,
}))
// @Form.create()
class MenuList extends PureComponent {
  state = {
    selectedKey: null
  };

  componentDidMount() {
    this.fetchList();
  }

  /**
   * 选择菜单项
   */
  onSelect = (selectedKeys) => {
    console.log(selectedKeys)
    const { dispatch } = this.props;
    this.setState({
      selectedKey: selectedKeys[0]
    })
    if (selectedKeys.length > 0) {
      dispatch({
        type: 'authMenu/get',
        payload: selectedKeys[0]
      })
    } else {
      dispatch({
        type: 'authMenu/reset'
      })
    }
  };

  /**
   * 点击新增重置表单
   */
  handleReset = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'authMenu/reset'
    })
  };

  /**
   * 新增
   */
  handleAdd = fields => {
    const { dispatch } = this.props;
    console.log(fields)
    dispatch({
      type: 'authMenu/add',
      payload: {
        ...fields
      },
    })
  };

  /**
   * 更新
   */
  handleUpdate = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'authMenu/update',
      payload: {
        ...fields
      },
    }).then((res) => {
      console.log(res)
    });
  };

  /**
   * 删除
   */
  handleDel = (selectKey) => {
    const that = this;
    Modal.confirm({
      title: `确定删除此项 ?`,
      okText: "确认",
      cancelText: "取消",
      onOk() {
        that.props.dispatch({
          type: 'authMenu/del',
          payload: selectKey
        })
      },
    });
  }

  /**
   * 获取菜单列表
   */
  fetchList() {
    const { dispatch } = this.props;
    dispatch({
      type: 'authMenu/list'
    })
  }

  render() {
    const { selectedKey } = this.state;
    const { authMenu: { list } } = this.props;

    const parentMethods = {
      handleUpdate: this.handleUpdate,
      handleAdd: this.handleAdd,
    };

    return (
      <PageHeaderWrapper title="菜单管理">
        <Row gutter={16}>
          <Col span={8}>
            <Card bordered={false}>
              <div className={styles.tableList}>
                <div className={styles.tableListOperator}>
                  <Button icon="plus" type="primary" onClick={() => this.handleReset()}>新建</Button>
                  {selectedKey && (
                    <span>
                      <Button icon="delete" onClick={() => this.handleDel(selectedKey)}>删除</Button>
                    </span>
                  )}
                </div>
                {
                  !list.length ? <Spin /> : (
                    <Tree
                      showIcon
                      defaultExpandAll
                      onCheck={this.onCheck}
                      onSelect={this.onSelect}
                    >
                      {list && Object.keys(list).length ?
                        (list.map(levelOne => (
                          <TreeNode icon={levelOne.resourceType === 'menu' ? <Icon type={levelOne.icon} /> : <Icon type="instagram" />} title={levelOne.menuDesc} key={levelOne.menuId}>
                            {levelOne.children && Object.keys(levelOne.children).length ? (
                              levelOne.children.map(levelTwo => (
                                <TreeNode icon={levelTwo.resourceType === 'menu' ? <Icon type={levelTwo.icon} /> : <Icon type="instagram" />} title={levelTwo.menuDesc} key={levelTwo.menuId}>
                                  {levelTwo.children && Object.keys(levelTwo.children).length ? (
                                    levelTwo.children.map(levelThree => (
                                      <TreeNode icon={levelThree.resourceType === 'menu' ? <Icon type={levelThree.icon} /> : <Icon type="instagram" />} title={levelThree.menuDesc} key={levelThree.menuId} />
                                    ))
                                  ) : null}
                                </TreeNode>
                              ))
                            ) : null}
                          </TreeNode>
                        )
                        )) : null}
                    </Tree>
                  )}
              </div>
            </Card>
          </Col>
          <Col span={16}>
            <Card>
              <AddOrUpdateForm
                {...parentMethods}
              />
            </Card>
          </Col>
        </Row>

      </PageHeaderWrapper>
    )
  }
}

export default MenuList;